package cn.org.donald.sensitive.model;

import cn.org.donald.sensitive.factory.*;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Path;

/**
 * @author Donald
 * @since 2023-11-10 14:59:27
 **/
public enum FactoryEnum {
    UNKNOWN("", UnknownFindSensitive.class, "未知类型"),
    TXT(".txt", TxtFindSensitive.class, "文本类型"),
    XLS(".xls", ExcelFindSensitive.class, "Excel类型"),
    XLSX(".xlsx", ExcelFindSensitive.class, "Excel类型"),
    DOCX(".docx", WordFindSensitive.class, "Word类型"),
    DOC(".doc", WordFindSensitive.class, "Word类型"),
    PPT(".ppt", PowerPointFindSensitive.class, "PowerPoint类型"),
    PPTX(".pptx", PowerPointFindSensitive.class, "PowerPoint类型"),
    PDF(".pdf", PdfFindSensitive.class, "PDF类型"),
    ;

    private final String fileExtension;

    private final Class<? extends IFindSensitive> implementClass;

    private final String desc;

    public String getFileExtension() {
        return fileExtension;
    }

    public Class<? extends IFindSensitive> getImplementClass() {
        return implementClass;
    }

    public String getDesc() {
        return desc;
    }

    FactoryEnum(String fileExtension, Class<? extends IFindSensitive> implementClass, String desc) {
        this.fileExtension = fileExtension;
        this.implementClass = implementClass;
        this.desc = desc;
    }

    public static FactoryEnum resolve(Path filePath) {
        String filePathStr = filePath.toString();
        int beginIndex = filePathStr.lastIndexOf(".");
        if (beginIndex != -1) {
            String extension = filePathStr.substring(beginIndex);
            for (FactoryEnum value : values()) {
                if (value.fileExtension.equalsIgnoreCase(extension)) {
                    return value;
                }
            }
        }
        return UNKNOWN;
    }

    public static IFindSensitive getInstance(Path filePath) {
        String filePathStr = filePath.toString();
        int beginIndex = filePathStr.lastIndexOf(".");
        FactoryEnum factoryEnum = UNKNOWN;
        if (beginIndex != -1) {
            String extension = filePathStr.substring(beginIndex);
            for (FactoryEnum value : values()) {
                if (value.fileExtension.equalsIgnoreCase(extension)) {
                    factoryEnum = value;
                }
            }
        }


        try {
            Class<? extends IFindSensitive> implementClass = factoryEnum.getImplementClass();
            Constructor<? extends IFindSensitive> constructor = implementClass.getConstructor(Path.class, FactoryEnum.class);
            return constructor.newInstance(filePath, factoryEnum);
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            throw new  RuntimeException(e);
        }
    }
}
